package shmallarchitect.web.pages;

import java.io.IOException;
import javax.faces.application.FacesMessage;
import javax.faces.component.html.HtmlInputSecret;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import shmallarchitect.faces.util.UserUtil;
import shmallarchitect.jpa.entities.User;

/**
 * @version Login.java
 * @version Created on 2009-08-31, 20:34:40
 * @author jaccus
 */
public class Login {

    private HtmlInputText userid;
    private HtmlInputSecret password;
    private final static String AUTH_USER = "Authorized_User";

    public Login() {
    }

    public String login() {
        //Grab UserRegistry Managed Bean


        // Call findByUserCredentials method
        // and retrieve currentUser which matches credentials
        User currentUser =
                UserUtil.findUserByCredentials(userid.getValue().toString(), password.getValue().toString());

        if (currentUser == null) {
            // login failed
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage("Invalid Login!"));
            return "failure";
        } else {
            // login success
//            JSFUtil.storeOnSession(FacesContext.getCurrentInstance(), "User", new User());
            User managedUserBean = (User) JSFUtil.getManagedObject("UserBean");
            UserUtil.copyUserProperties(currentUser, managedUserBean);
            managedUserBean.setIsAdmin(true); //=isLoggedIn

            // Place authorized user on session to disable security filter
            JSFUtil.storeOnSession(FacesContext.getCurrentInstance(), AUTH_USER, "Authorized_User");
            return "success";
        }
    }

    public String logout() throws IOException {
        ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse response = (HttpServletResponse) ectx.getResponse();
        HttpSession session = (HttpSession) ectx.getSession(false);
        session.invalidate();

        //FacesContext ctx = FacesContext.getCurrentInstance();
        //Application app = ctx.getApplication();
        //app.getNavigationHandler().handleNavigation(ctx, "/welcome.jsp", "welcome");

        // To avoid using the navigation handler you could also use...
        //response.sendRedirect("../index.jsp");
        return "success";

    }

    public void setUserid(HtmlInputText userid) {
        this.userid = userid;
    }

    public HtmlInputText getUserid() {
        return userid;
    }

    public void setPassword(HtmlInputSecret password) {
        this.password = password;
    }

    public HtmlInputSecret getPassword() {
        return password;
    }
}

